package com.lm.survey.util;

import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import com.lm.survey.model.Role;
import com.lm.survey.model.User;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.*;
import com.thoughtworks.xstream.io.json.*;

public class JsonHelper {
	public static String object2json(Object o){
		XStream xstream = getXStream();
		return xstream.toXML(o);
	}
	
	public static String list2json(List list){
		XStream xstream = getXStream();
		xstream.setMode(XStream.NO_REFERENCES);
		return xstream.toXML(list);
	}
	

	
	
	
	public static XStream getXStream(){
		XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
		    public HierarchicalStreamWriter createWriter(Writer writer) {
		        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
		    }
		});
		return xstream;
	}
	
	
	public static String createRsp(boolean isSuccess,String msg,String... msgPair){
		StringBuilder sb = new StringBuilder();
		if(isSuccess){
			sb.append("{success:true,author:'lm',");
		}else{
			sb.append("{success:false,author:'lm',");
		}
		
		if(msgPair.length!=0){
			sb.append("submsgs:{");
			for(int i=0;i<msgPair.length;i++){
				sb.append(msgPair[i]).append(":").append(msgPair[++i]).append(",");
			}
			sb.setLength(sb.length()-1);
			sb.append("},");
		}
		sb.append("msg:'").append(msg).append("'}");
		return sb.toString();
	}
	
	public static void main(String[] args){
		{
//			User user = new User();
//			user.setEnable(1);
//			user.setId(123232332);
//			user.setPassword("1232323");
//			user.setUserName("hello");
//			Role role = new Role("1");
//			user.setRole(new Role[]{role});
//			System.out.println(object2json(user));
		}
		{
			List list = new ArrayList();
			User user = new User();
			user.setEnable(1);
			user.setId(123232332);
			list.add(user);
			user = new User();
			user.setEnable(1);
			user.setId(22323);
			list.add(user);
			System.out.println(list2json(list));
			
		}
		
	}
}
